package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.FollowUser;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service(version = "1.0.0")
public class VideoApiImpl implements VideoApi {

    @Autowired
    private IdService idService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String VIDEO_FOLLOW_USER_KEY_PREFIX = "VIDEO_FOLLOW_USER_";

    /**
     * 发布小视频
     *
     * @param video
     * @return
     */
    @Override
    public String saveVideo(Video video) {
        try {
            //校验, 如果查询数据都为空, 则直接返回null
            if (ObjectUtil.isAllEmpty(video.getUserId(), video.getPicUrl(), video.getVideoUrl())) {
                return null;
            }
            //设置id
            video.setId(ObjectId.get());
            video.setVid(idService.createId(IdType.VIDEO));
            //发布时间
            video.setCreated(System.currentTimeMillis());
            //保存到MongoDB中
            mongoTemplate.save(video);
            return video.getId().toHexString();
        } catch (Exception e) {
            log.error("小视频发布失败~ video = " + video, e);
        }
        return null;
    }

    /**
     * 分页查询小视频列表, 按照时间倒序排序
     * 查询小视频列表，优先展现推荐的视频，如果没有推荐的视频或已经查询完成，就需要查询系统视频数据
     *
     * @param userId   用户id
     * @param page     页码
     * @param pageSize 每页显示的条数
     * @return
     */
    @Override
    public PageInfo<Video> queryVideoList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Video> pageInfo = new PageInfo();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        //从redis中获取推荐视频的数据
        String redisKey = "QUANZI_VIDEO_RECOMMEND_" + userId;
        String redisData = redisTemplate.opsForValue().get(redisKey);
        List<Long> vids = new ArrayList<>();
        int recommendCount = 0;
        if (StrUtil.isNotEmpty(redisData)) {
            //手动分页查询数据
            List<String> vidList = StrUtil.split(redisData, ',');
            recommendCount = vidList.size();
            //计算分页
            int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
            int start = startEnd[0];
            int end = Math.min(startEnd[1], recommendCount);
            for (int i = start; i < end; i++) {
                vids.add(Convert.toLong(vidList.get(i)));
            }
        }
        if (CollUtil.isEmpty(vids)) {
            //没有推荐视频或是推荐视频已刷完, 查询系统的视频数据
            //计算前面的推荐视频页数
            int totalPage = PageUtil.totalPage(recommendCount, pageSize);
            PageRequest pageRequest = PageRequest.of(page - totalPage - 1, pageSize, Sort.by(Sort.Order.desc("created")));
            //查询数据库中的视频数据
            Query query = new Query().with(pageRequest);
            List<Video> videoList = mongoTemplate.find(query, Video.class);
            pageInfo.setRecords(videoList);
            return pageInfo;
        }
        //根据vid查询对应的视频数据
        Query query = Query.query(Criteria.where("vid").in(vids));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        pageInfo.setRecords(videoList);
        return pageInfo;
    }

    /**
     * 根据id查询视频对象
     *
     * @param videoId
     * @return
     */
    @Override
    public Video queryVideoById(String videoId) {
        return mongoTemplate.findById(new ObjectId(videoId), Video.class);
    }

    /**
     * 关注用户
     *
     * @param userId       当前用户
     * @param followUserId 关注的目标用户
     * @return
     */
    @Override
    public Boolean followUser(Long userId, Long followUserId) {
        if (ObjectUtil.isAllEmpty(userId, followUserId)) {
            return false;
        }

        try {
            //查询是否已经关注, 如果已经关注直接返回
            if (isFollowUser(userId, followUserId)) {
                return false;
            }
            //将用户的关注列表保存到redis中, 方便后续查询
            FollowUser followUser = new FollowUser();
            followUser.setId(ObjectId.get());
            followUser.setUserId(userId);
            followUser.setFollowUserId(followUserId);
            followUser.setCreated(System.currentTimeMillis());
            mongoTemplate.save(followUser);

            //保存到redis中
            String redisKey = getVideoFollowUserKey(userId);
            String hashKey = String.valueOf(followUserId);
            redisTemplate.opsForHash().put(redisKey, hashKey, "1");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 取消关注用户
     *
     * @param userId       当前用户
     * @param followUserId 关注的目标用户
     * @return
     */
    @Override
    public Boolean disFollowUser(Long userId, Long followUserId) {
        if (ObjectUtil.isAllEmpty(userId, followUserId)) {
            return false;
        }
        try {
            if (!isFollowUser(userId, followUserId)) {
                return false;
            }
            //取消关注, 删除关注数据即可
            Query query = Query.query(Criteria.where("userId").is(userId).and("followUserId").is(followUserId));
            DeleteResult result = mongoTemplate.remove(query, FollowUser.class);
            if (result.getDeletedCount() > 0) {
                //删除redis中的数据
                String redisKey = this.getVideoFollowUserKey(userId);
                String hashKey = String.valueOf(followUserId);
                redisTemplate.opsForHash().delete(redisKey, hashKey);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询用户是否关注某个用户
     *
     * @param userId       当前用户
     * @param followUserId 关注的目标用户
     * @return
     */
    @Override
    public Boolean isFollowUser(Long userId, Long followUserId) {
        String redisKey = this.getVideoFollowUserKey(userId);
        String hashKey = String.valueOf(followUserId);
        return redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }


    @Override
    public List<Video> queryVideoCountByUid(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        for (Video video : videoList) {
            System.out.println(video);
        }
        return videoList;
    }


    /**
     * 根据id查询用户发布的视频
     *
     * @param userId
     * @return
     */
    @Override
//    public List<Video> queryVideoCountById(Long userId, Integer page, Integer pageSize, String sortProp, String sortOrder) {
    public PageInfo<Video> queryVideoCountById(Long userId, Integer page, Integer pageSize, String sortProp, String sortOrder) {

        PageInfo<Video> pageInfo = new PageInfo<>();
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(page);


        PageRequest pageRequest = null;
        //判断是升序
        if (sortOrder.equals("ascending")) {
            pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.asc(sortProp)));
        }

        //判断是降序
        if (sortOrder.equals("descending")) {
            pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc(sortProp)));
        }

        //PageRequest pageRequest = PageRequest.of(page - 1, pageSize);

        //获取对应用户的分页数据
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageRequest);
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        //获取需要的用户视频总数
        Query query1 = Query.query(Criteria.where("userId").is(userId));
        List<Video> videoList1 = mongoTemplate.find(query1, Video.class);

        //传入当前页的数据
        pageInfo.setRecords(videoList);
        //传入总数
        pageInfo.setTotal(videoList1.size());

        return pageInfo;
    }


    private String getVideoFollowUserKey(Long userId) {
        return VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
    }

}
